package 链表题目;

import 链表题目.model.ListNode;


// 合并两个有序链表
//https://leetcode.cn/problems/merge-two-sorted-lists/description/
class 合并两个有序链表 {
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode ans = new ListNode(0, list2);
        ListNode temp = ans;
        while (list1 != null || list2 != null) {
            if (list1 == null) {
                temp.next = list2;
                break;
            }
            if (list2 == null) {
                temp.next = list1;
                break;
            }
            if (list1.val < list2.val) {
                temp.next = list1;
                list1 = list1.next;
            } else {
                temp.next = list2;
                list2 = list2.next;
            }
            temp = temp.next;
        }
        return ans.next;
    }

    public static void main(String[] args) {
        ListNode one3 = new ListNode(4, null);
        ListNode one2 = new ListNode(2, one3);
        ListNode one1 = new ListNode(1, one2);
        ListNode tow3 = new ListNode(4, null);
        ListNode tow2 = new ListNode(3, tow3);
        ListNode tow1 = new ListNode(1, tow2);
        ListNode listNode = new 合并两个有序链表().mergeTwoLists(one1, tow1);
        System.out.println(listNode);
    }
}
